package com.wz.datachannel.app;

import java.util.ArrayList;
import java.util.List;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.wz.datachannel.interfaces.IGetSerListener;
import com.wz.datachannel.interfaces.IGetSerListener.RouteAddr;
import com.wz.datachannel.model.RouteResult;
import com.wz.datachannel.util.FastJsonUtil;
import com.wz.datachannel.util.HttpClientUtil;
import com.wz.datachannel.util.Utils;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Looper;
import cz.msebera.android.httpclient.Header;

/**
 * 全局应用程序类
 */
public class AppContext extends Application {

	private static AppContext instance;
	private static Context applicationContext;

	private boolean isShutDown = false;//是否关机，关机后任何操作不再进行

	public static Context getAppContext() {
		return applicationContext;
	}

	public boolean isShutDown() {
		return isShutDown;
	}

	public void setShutDown(boolean isShutDown) {
		this.isShutDown = isShutDown;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		applicationContext = getApplicationContext();
		// 注册App异常崩溃处理器
//		Thread.setDefaultUncaughtExceptionHandler(AppException.getAppExceptionHandler());
		LocalData.init(this);
		instance = this;
	}

	/**
	 * 获取Application
	 * 
	 * @return
	 */
	public static AppContext getInstance() {
		return instance;
	}

	/**
	 * 获取App安装包信息
	 * 
	 * @return
	 */
	public PackageInfo getPackageInfo() {
		PackageInfo info = null;
		try {
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace(System.err);
		}
		if (info == null)
			info = new PackageInfo();
		return info;
	}

	public boolean isFirstLogin() {
		return get("KEY_FRIST_START", true);
	}

	public void setFristStart(boolean frist) {
		set("KEY_FRIST_START", frist);
	}

	//sp相关 =====start=======
	private static boolean sIsAtLeastGB;

	static {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			sIsAtLeastGB = true;
		}
	}

	public void apply(SharedPreferences.Editor editor) {
		if (sIsAtLeastGB) {
			editor.apply();
		} else {
			editor.commit();
		}
	}

	public SharedPreferences getPreferences() {
		return getSharedPreferences(LocalData.userId, Context.MODE_MULTI_PROCESS);
	}

	public void set(String key, boolean value) {
		Editor editor = getPreferences().edit();
		editor.putBoolean(key, value);
		apply(editor);
	}

	public boolean get(String key, boolean defValue) {
		return getPreferences().getBoolean(key, defValue);
	}
	//sp相关 =====end=======

	/**
	 * 获取服务器地址（同步获取）
	 * @author wei 
	 * @param listener
	 */
	public void getSerAddr(final IGetSerListener listener) {
		if (null == listener) {
			return;
		}
		boolean isFirstLogin = isFirstLogin();
		RequestParams params = new RequestParams();
		if (isFirstLogin) {
			params.put("isfrist", 1);
		}
		params.put("usertype", 1);//8宝账号
		params.put("userid", LocalData.userId);
		params.put("md5pass", LocalData.userPasswd);
		params.put("terminal", 0);//0：灵机 ，1：手机
		//getBuilder.addParams("bitmode", "none");//none=普通模式
		try {
			Looper.prepare();
		} catch (Exception e) {
		}

		//HttpClientUtil.getClient(true).get("http://test.im.web.wizhong.com:8098/clientEntry", params, new TextHttpResponseHandler() {
			//HttpClientUtil.getClient(true).get("http://192.168.1.240:80/IMWebServer/clientEntry", params, new TextHttpResponseHandler() {
			HttpClientUtil.getClient(true).get("http://im.web.wizhong.com/clientEntry", params, new TextHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				RouteResult routeResult = FastJsonUtil.parseJsonToBean(responseString, RouteResult.class);
				if (null == routeResult || routeResult.getResultCode() < 1 || Utils.isListEmpty(routeResult.getServerlist())) {
					String errMsg = "";
					try {
						errMsg = routeResult.getResultMsg();
					} catch (Exception e) {
					}
					listener.onFailed(errMsg);
				} else {
					List<String> list = routeResult.getServerlist();
					List<RouteAddr> routeList = new ArrayList<RouteAddr>();
					for (String string : list) {
						List<String> addrlist = Utils.StringToStrList(string, ":");
						try {
							RouteAddr routeAddr = new RouteAddr();
							routeAddr.ip = addrlist.get(0);
							routeAddr.port = Integer.valueOf(addrlist.get(1));
							routeList.add(routeAddr);
						} catch (Exception e) {
						}
					}

					if (Utils.isListEmpty(routeList)) {
						listener.onFailed("server list is Empty");
					} else {
						listener.onSuccess(routeList);
						setFristStart(false);
					}
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				listener.onFailed(responseString);
			}
		});
	}

}